package spring.cloud.tasks.tasks_manager.tasks_manager.listener;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent.Type;
import spring.cloud.tasks.tasks_manager.tasks_manager.node.Node;
import spring.cloud.tasks.tasks_manager.tasks_manager.service.TaskListenersService;

@Slf4j
@Setter
@Getter
public class TaskAddOrRemoveListener extends TreeCacheListener {
    private TaskListenersService taskListenersService;

    public TaskAddOrRemoveListener(TaskListenersService addOrRemoveTaskListenersService) {
        this.taskListenersService = addOrRemoveTaskListenersService;
    }

    @Override
    public void childEvent(Type type, String path, String nodeData) throws Exception {
        try {
            String taskId = StringUtils.substringAfterLast(path, "/");
            if (!Node.JOBS_NODE.equals(taskId)) {
                if (isAddTask(type)) {
                    log.info("job: {} created", taskId);
                    taskListenersService.addTaskListener(taskId);
                } else if (isRemoveTask(type)) {
                    log.info("job: {} removed", taskId);
                    taskListenersService.removeTaskTreeCache(taskId);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    private boolean isAddTask(TreeCacheEvent.Type type) {
        return type == TreeCacheEvent.Type.NODE_ADDED;
    }

    private boolean isRemoveTask(TreeCacheEvent.Type type) {
        return type == TreeCacheEvent.Type.NODE_REMOVED;
    }
}
